<template>
  <div class="ai-chat">
    <!-- 聊天消息显示区域 -->
    <div class="chat-messages">
      <div
        v-for="(message, index) in history_messages"
        :key="index"
        :class="{
          'user-message': message.sender === 'user',
          'ai-message': message.sender === 'ai',
        }"
      >
        {{ message.text }}
        <img v-if="message.img" :src="message.img" alt="Message Image">
      </div>
    </div>
    <!-- 输入框和发送按钮 -->
    <div class="chat-input">
      <!-- <input
        v-model="inputMessage"
        type="text"
        placeholder="输入你的消息..."
        @keyup.enter="handleSend"
      /> -->
      <textarea
        v-model="input_box_message"
        placeholder="输入信息..."
        @keydown.enter.prevent="handleSend"
      ></textarea>
      <button @click="handleSend">发送</button>
      <!-- 语音输入按钮 -->
      <button @click="startVoiceInput" :class="{ active: isRecognizing }">
        {{ isRecognizing ? '停止' : '🎤 语音' }}
      </button>
      <!-- 新增重置场景图按钮 -->
      <button @click="resetSceneGraph">
        重置场景图
      </button>
      <!-- <InputPanel v-model:message="message" @send="sendMessage" @reset="resetSceneGraph" /> -->
      <!-- <button @click="sendMessage">发送</button> -->
    </div>
  </div>
</template>


<!-- <script>
export default {
  data() {
    return {
      messages: [], // 存储聊天消息的数组
      inputMessage: '', // 存储用户输入的消息
    }
  },
  methods: {
    handleSend() {
      if (this.inputMessage.trim() === '') return
      // 将用户消息添加到消息列表中
      this.messages.push({ sender: 'user', text: this.inputMessage })
      // 模拟 AI 回复
      this.simulateAIResponse()
      // 清空输入框
      this.inputMessage = ''
    },
    simulateAIResponse() {
      // 模拟 AI 回复，实际应用中需要调用真实的 AI API
      setTimeout(() => {
        const aiReply = '这是 AI 的回复。'
        this.messages.push({ sender: 'ai', text: aiReply })
      }, 1000)
    },
  },
}
</script> -->

<style scoped>
.ai-chat {
  display: flex;
  flex-direction: column;
  height: 88vh;
  border: 1.5px solid #A6A6A6;
  border-radius: 0px 0px 8px 8px;
  overflow: hidden;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.user-message {
  text-align: right;
  background-color: #D9D9D9;
  padding: 5px;
  margin: 5px;
  border-radius: 5px;
}

.ai-message {
  text-align: left;
  background-color: #D4E3F9;
  padding: 5px;
  margin: 5px;
  border-radius: 5px;
}

.ai-message img{
  width: 60%;
  margin-top: 1%;
  margin-bottom: 0.5%;
  margin-left: 20%;
  margin-right: 20%;
  border-radius: 6px;
}

.chat-input {
  display: flex;
  align-items: center ;
  padding: 10px;
  border-top: 1.5px solid #A6A6A6;
  height: 4vh;

}

.chat-input input {
  flex: 1;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 8px;
  height: 30px
}

.chat-input textarea {
  flex: 1;
  height: 20px; /* 与按钮高度统一 */
  padding: 8px 12px; /* 舒适内边距 */
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  resize: none;
  font-family: inherit;
  font-size: 14px; /* 稍小字体 */
  line-height: 1.4;
  background-color: #ffffff;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05); /* 内阴影 */
  transition:
    border-color 0.2s ease,
    box-shadow 0.2s ease;
}


.chat-input button {
  margin-left: 6px;
  padding: 5px 10px;
  background: #3773e1;
  color: #ffffff;
  border: none;
  border-radius: 6px 6px 6px 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  height: 36px; /* 与文本框高度一致 */
  transition:
    background 0.3s ease,
    transform 0.1s ease;
}

button:hover {
  background: linear-gradient(90deg, #009e8f, #3a6da5); /* 悬浮时颜色加深 */
  background: #0553e4;
}

button:active {
  transform: translateY(1px); /* 按下时下沉 */
}

button.active {
  background: #ff4444; /* 语音识别时红色 */
}

button.active:hover {
  background: #e03e3e;
}

</style>

<script setup>
import { ref } from 'vue'

const emit = defineEmits(['send', 'reset'])
const input_box_message = ref('')
const history_messages = ref([])
const isRecognizing = ref(false) // 识别状态标志
let mediaRecorder = null
let audioChunks = []

const showMessage = (message, imgUrl) => {
  history_messages.value.push({ sender: 'ai', text: message, img:imgUrl })
}

// 发送信息
const handleSend = () => {
  if (isRecognizing.value) {
    stopRecording() // 发送时停止语音识别
  }
  const content = input_box_message.value.trim()
  if (!content) {
    alert('请输入消息')
    return
  }
  history_messages.value.push({ sender: 'user', text: input_box_message.value })
  emit('send', content) // 发送消息
  input_box_message.value = ''
}

// 开始录音
const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    const options = { mimeType: 'audio/webm' } // 录制为 WebM 格式
    mediaRecorder = new MediaRecorder(stream, options)
    mediaRecorder.ondataavailable = (event) => {
      audioChunks.push(event.data)
    }
    mediaRecorder.onstop = async () => {
      const audioBlob = new Blob(audioChunks, { type: 'audio/webm' })
      const formData = new FormData()
      formData.append('audio', audioBlob, 'audio.webm')

      try {
        const response = await fetch('http://127.0.0.1:5000/asr', {
          method: 'POST',
          body: formData,
        })
        if (!response.ok) {
          const text = await response.text()
          throw new Error(`HTTP error! status: ${response.status}, body: ${text}`)
        }
        const data = await response.json()
        console.log('识别结果:', data)
        input_box_message.value = data.text // 更新文本框内容
      } catch (error) {
        console.error('发送请求错误:', error)
      } finally {
        audioChunks = []
      }
    }
    mediaRecorder.start()
    isRecognizing.value = true
  } catch (err) {
    console.error('录音设备错误:', err)
    alert('无法访问音频设备')
  }
}

// 停止录音
const stopRecording = () => {
  if (mediaRecorder && mediaRecorder.state !== 'inactive') {
    mediaRecorder.stop()
    isRecognizing.value = false // 停止录音时更新按钮状态
  }
}

// 启动或停止语音输入
const startVoiceInput = () => {
  if (isRecognizing.value) {
    stopRecording() // 停止录音
  } else {
    startRecording() // 开始录音
  }
}

// 重置场景图
const resetSceneGraph = () => {
  emit('reset') // 触发自定义事件通知父组件
}

defineExpose({
  showMessage
});
</script>


